<template>
  <div>
    <!-- quill-editor插件标签 分别绑定各个事件-->
    <quill-editor
      :ref="refValue"
      v-model="content"
      :options="editorOption"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    />
    <!-- 文件上传input 将它隐藏-->
    <el-upload
      ref="upload"
      :action="`${baseUrl}/upload`"
      :headers="{
        'Authorization':token
      }"
      accept="image/*"
      class="avatar-uploader"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      style="display:none"
    >
      <el-button
        size="small"
        type="primary"
        class="imgInput"
        element-loading-text="插入中,请稍候"
      >点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import { getToken } from '@/utils/auth'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  components: {
    quillEditor
  },
  props: {
    contents: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    refValue: {
      type: String,
      default: 'myQuillEditor'
    },
    index: {
      type: Number,
      default: 0
    },
    refUpload: {
      type: String,
      default: 'upload'
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      token: 'Bearer ' + getToken(),
      content: '', // 文章内容
      editorOption: {
        placeholder: '请输入内容',
        modules: {
          //   配置富文本
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            // [{ header: 1 }, { header: 2 }],
            // [{ direction: "rtl" }],
            [{ size: ['small', false, 'large', 'huge'] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }],
            // [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['link', 'image']
          ]
        }
      },
      addRange: [],
      uploadData: {},
      photoUrl: '', // 上传图片地址
      uploadType: '' // 上传的文件类型（图片、视频）
    }
  },
  watch: {
    content: function() {
      this.$emit('getSon', this.content)
    },
    contents: function(newVal, oldVal) {
      this.content = newVal
    }
  },
  created() {
    console.log()
    this.$refs[this.refValue] = HTMLInputElement
    this.$refs = {
      // myQuillEditor: HTMLInputElement,
      imgInput: HTMLInputElement
    }
    if (this.contents) {
      this.content = this.contents
    }
  },
  // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件
  mounted() {
    // 为图片ICON绑定事件 getModule 为编辑器的内部属性
    // console.log(this.$refs.myQuillEditor.quill);
    this.$refs[this.refValue].quill
      .getModule('toolbar')
      .addHandler('image', this.imgHandler)
    this.$refs[this.refValue].quill
      .getModule('toolbar')
      .addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  },
  methods: {
    onEditorFocus(val, editor) { // 富文本获得焦点时的事件
      // console.log(val); // 富文本获得焦点时的内容
      this.$refs[this.refValue].quill.enable(!this.disabled) // 在获取焦点的时候禁用
    },
    // 图片上传之前调取的函数
    // 这个钩子还支持 promise
    handleAvatarSuccess(data) {
      const { code, url } = data
      if (code === 200) {
        const { quill } = this.$refs[this.refValue]
        const length = quill.getSelection(true).index
        // 获取光标所在位置
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      }
    },

    // 点击图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.$refs[this.refValue].quill.getSelection()
      if (state) {
        const fileInput = document.getElementsByClassName('imgInput')[this.index]
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'image'
    },
    onEditorChange({ editor, html, text }) {
      // console.log("editor change!", html);
      this.content = html
    },
    // 点击视频ICON触发事件
    videoHandler(state) {
      this.addRange = this.$refs[this.refValue].quill.getSelection()
      if (state) {
        const fileInput = document.getElementsByClassName('imgInput')[this.index]
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'video'
    },
    getCover() {}
  }
}
</script>

<style lang="scss">
.quill-editor {
  min-height: 500px;
  background: #fff;
}
.ql-container {
  min-height: 500px;
}
.ql-snow .ql-editor img {
  max-width: 480px;
}
.ql-editor .ql-video {
  max-width: 480px;
}
</style>
